const Router = require('koa-router')
const mysql = require('../util/mysql/mysql')
const { url } = require('../util/qiniu/config')
const { SUCCESS, FAIL, USER_ACCOUNT_EXIST } = require('../util/respone/index')

let banners = new Router()

// 获取轮播图
banners.get('/banners', async (ctx, next) => {
  // 拼接 查询数据库 语句
  let checkSql = 'SELECT * FROM banners'

  // -------数据库操作------
  // 查询数据库中数据
  await mysql.check(checkSql)
    .then(async res => {
      await SUCCESS(ctx,res,"获取banners成功！")
    })
    .catch(async err => {
      return await FAIL(ctx, '获取banners出错!')
    })
})


// 添加轮播图
banners.post('/banners', async (ctx, next) => {
  // 用户post过来的数据
  let { urlArr } = ctx.request.body;
  
  // -------数据库操作------
  setBanner(urlArr)
})

async function setBanner(params) {
  if (params.length > 0) {
    let temp = params.shift()
    let addSql = 'INSERT INTO banners(imgUrl) VALUES(?)'
    let addSqlParams = [temp]
    await mysql.add(addSql, addSqlParams)
      .then(async res => {
        console.log(temp, 'set banners success')
        setBanner(params)
      })
      .catch(async err => {
        return await FAIL(ctx, '添加banners出错!')
    })
  } else {
    return await SUCCESS(ctx,{},"添加banners成功！")
  }
}

// 删除轮播图
banners.delete('/banners', async (ctx, next) => {
  let { id } = ctx.request.body

  if (!id) {
    return await PARAM_NOT_COMPLETE(ctx)
  }
  
  // -----数据库操作-------
  let delSql = `DELETE FROM banners WHERE id = "${id}"`
  await mysql.delete(delSql)
    .then(async res => {
      await SUCCESS(ctx,{},"删除图片成功！")
    })
    .catch(async err => {
      return await FAIL(ctx, '删除图片出错!')
  })
})

module.exports = { banners }